<template>
  <basic-container>
    <!-- <avue-crud :option="option"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :before-open="beforeOpen"
               :cell-style="cellStyle"
               :row-style="rowStyle"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"> -->
    <avue-crud :option="option"
               :data="data"
               ref="crud"
               v-model="form"
               :permission="permissionList"
               :before-open="beforeOpen"
               @row-del="rowDel"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"
               @keydown.native="keydown($event)"
              >
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   v-if="permission.dept_delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button
          v-if="hasEditDeBtn(scope.row)"
          type="text"
          icon="el-icon-watch"
          size="small"
          @click.stop="handleEditDelivery(scope.row)"
        >超时配送权限</el-button>
      </template>
      <template slot-scope="scope" slot="isOverTimeSms">
        <span>{{deliverySmsMap[scope.row.isOverTimeSms] || '-'}}</span>
      </template>
      
    </avue-crud>

    <editDeliverySmsDialog ref="editDeliverySmsDialog" @editSuccess="onEditSmsSuccess"></editDeliverySmsDialog>
  </basic-container>
</template>

<script>
  import {add, getDept, getDeptTree, getList, remove, update} from "@/api/system/dept";
  import {mapGetters} from "vuex";
  import website from '@/config/website';
  import editDeliverySmsDialog from "./editDeliverySmsDialog.vue";
  const deliverySmsMap = {
    0: '否',
    1: '是',
  }

  export default {
    data() {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入城市名称'));
        } else {
          this.form.deptName = value.replace(/[^\u4E00-\u9FA5]/g, '')
          callback();
        }
      };
      var fullNamePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入城市全称'));
        } else {
          this.form.fullName = value.replace(/\s+/g, '')
          callback();
        }
      };
      return {
        form: {},
        selectionList: [],
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          menuWidth: 150,
          tip: false,
          tree: true,
          border: true,
          index: true,
          columnBtn: false, // 列显隐按钮
          refreshBtn: false, // 刷新按钮
          searchBtn: false, // 搜索显隐按钮（当 column 中有搜索的属性，或则 searchsolt 为 true 时自定义搜索启动起作用）
          selection: true,
          viewBtn: true,
          column: [
            {
              label: "城市名称",
              prop: "deptName",
              search: true,
              // rules: [{
              //   required: true,
              //   message: "请输入城市名称",
              //   trigger: "blur"
              // }]
              rules: [{
                required: true,
                validator: validatePass,
                trigger: 'change'
              }]
            },
            {
              label: "所属租户",
              prop: "tenantId",
              type: "tree",
              dicUrl: "/api/xmbz-system/tenant/select",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: website.tenantMode,
              span: 24,
              props: {
                label: "tenantName",
                value: "tenantId"
              },
              // hide: !website.tenantMode,
              // search: website.tenantMode,
              hide: true,
              search: false,
              rules: [{
                required: true,
                message: "请输入所属租户",
                trigger: "click"
              }]
            },
            {
              label: "城市全称",
              prop: "fullName",
              search: true,
              rules: [{
                required: true,
                validator: fullNamePass,
                trigger: 'change'
              }]
            },
            {
              label: "上级城市",
              prop: "parentId",
              dicData: [],
              type: "tree",
              hide: true,
              width: 20,
              props: {
                label: "title"
              },
              rules: [{
                required: true,
                message: "请选择上级城市",
                trigger: "click"
              }]
            },

            {
              label: "排序",
              prop: "sort",
              type: "number",
              rules: [{
                required: true,
                message: "请输入排序",
                trigger: "blur"
              }]
            },

            {
              label: "备注",
              prop: "remark",
              span: 24,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            }
          ]
        },
        data: [],
        deliverySmsMap
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.dept_add, false),
          viewBtn: this.vaildData(this.permission.dept_view, false),
          delBtn: this.vaildData(this.permission.dept_delete, false),
          editBtn: this.vaildData(this.permission.dept_edit, false),
          // addBtn: false,
          // delBtn: false,
          // editBtn: false
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, loading, done) {
        if (this.form.sort < 0) {
          this.$message.warning("排序不能为负数，请重新编辑");
          done();
          return;
        }
        if(this.form.deptName == this.form.$parentId) {
          this.$message({
            message: '城市名称与上级城市不能重名，请重新编辑',
            type: 'warning'
          });
          done()
          return;
        }

        let cityArray = []// 城市
        let regionArray = []// 当前城市下区域
        let allRegionArray = []// 所有区域
        getDeptTree().then(res => {
          const result = res.data.data
          result.forEach($0 => {
            $0.children && $0.children.forEach($1 => {// 城市
              cityArray.push($1.title)
              if ($1.id === this.form.parentId) {
                regionArray = $1.children && $1.children.map($2 => $2.title)
              }
              $1.children && $1.children.forEach($2 => {
                allRegionArray.push($2.title)
              })
            })
          })

          if (allRegionArray.indexOf(this.form.$parentId) > -1) {
            this.$message({
              message: '层级最多可叠加两层，请重新编辑',
              type: 'warning'
            });
            done()
            return;
          }

          if(cityArray.includes(this.form.deptName)) {
            this.$message({
              message: '城市名存在重名，请重新编辑',
              type: 'warning'
            });
            done()
            return;
          }

          if(regionArray.includes(this.form.deptName)) {
            this.$message({
              message: '同层级区域名存在重名，请重新编辑',
              type: 'warning'
            });
            done()
            return;
          }

          add(row).then(() => {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, error => {
            console.log(error);
          }).finally(() => {
            done();
          })
        })
      },
      rowUpdate(row, index, loading, done) {
        // console.log('1111111',this.form)
        if (this.form.sort >= 0) {
          update(row).then(() => {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          }, error => {
            done();
            console.log(error);
          });
        } else {
          this.$message.warning("排序不能为负数，请重新编辑");
          done();
        }
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params) {
        this.query = params;
        this.onLoad(this.page, params);
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDept(this.form.id).then(res => {
            this.form = res.data.data;
            console.log('res.data.data',res.data.data)
          });
        }
        done();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        console.log('加载',this)
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          this.data = res.data.data;
          getDeptTree().then(res => {
            const data = res.data.data;
            const index = this.$refs.crud.findColumnIndex("parentId");
            this.option.column[index].dicData = data;
          });
        });
      },
      // 禁止输入空格
      keydown(event){
        if(event.keyCode == 32){
          event.returnValue = false
        }
      },
      handleEditDelivery(data) {
        this.$refs.editDeliverySmsDialog.show(data)
      },
      hasEditDeBtn(data) {
        return data.deptName.includes('市') && this.permission.dept_edit_delivery_sms
      },
      onEditSmsSuccess() {
        this.onLoad(this.page)
      },
      dynamicCol() {
        if (this.permission && this.permission.dept_edit_delivery_sms) {
          this.option.column.push({
            label: "是否支持超时配送短信",
            prop: "isOverTimeSms",
            slot: true,
            hide: false,
            display: false,
          })
        }
      }
    },
    components: {
      editDeliverySmsDialog
    },
    mounted() {
      this.dynamicCol()
    }
  };
</script>

<style>
</style>
